package com.controller;

import com.bean.Goods;
import com.service.IGoodsService;
import com.service.IOrderService;
import com.utils.R;
import org.slf4j.Logger;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * @author arthorn
 * @create 2022-04-27-9:44
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {
    //日志
    private static final Logger log = LoggerFactory.getLogger(GoodsController.class);

    @Autowired
    private IGoodsService goodService;


    //restful风格
    //增加新商品
    @PostMapping
    public R save(@RequestBody Goods goods)throws Exception{
        if(goods.getGoodsName().equalsIgnoreCase("123")){
            throw new Exception();
        }
        boolean flag = goodService.save(goods);
        return new R(flag,flag?"添加成功^_^!":"添加失败-_-!");
    }

    //删除商品
    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id){
        return new R(goodService.removeById(id));
    }

    //修改商品信息
    @PutMapping
    public R update(@RequestBody Goods good){
        return new R(goodService.updateById(good));
    }

    //查询所有非秒杀商品
    @GetMapping
    public R getAllgood()throws Exception{
        return new R(true,goodService.getGoodsList());
    }

    //用id查询单册商品
    @GetMapping("{id}")
    public R getById(@PathVariable Integer id){
        return new R(true,goodService.getById(id));
    }
    //分页
    /*@GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize){
        IPage<good> page = goodService.page(new Page<good>(currentPage,pageSize));

        if(currentPage>page.getPages()){
            page = goodService.page(new Page<>(page.getPages(),pageSize));
        }

        return new R(true,goodService.page(page));
    }*/
    //模糊查找分页
    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize,Goods good){

//        System.out.println("参数==>"+good);
        IPage<Goods> page = goodService.getPage(currentPage, pageSize,good);
        //如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        if(currentPage > page.getPages()){
            page = goodService.getPage((int)page.getPages(), pageSize,good);
        }
        /*ModelAndView modelAndView = new ModelAndView();
        List<good> goods = goodService.list();
        //设置模型
        modelAndView.addObject("goodList",goods);
        //设置视图
        modelAndView.setViewName("good-list");*/
        return new R(true, page);
    }
   /* //form保存商品
    @RequestMapping("/save")
    @ResponseBody
    public String postSave(good good){
        goodService.save(good);
        return "保存成功！您保存的数据为："+good;
    }*/


}
